package cn.bgs.controller;

import cn.bgs.common.Constants;
import cn.bgs.common.Results;
import cn.bgs.dao.StuMapper;
import cn.bgs.entity.*;
import cn.bgs.service.StuService;
import cn.bgs.service.StudentService;
import cn.bgs.service.impl.StuServiceImpl;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController

@RequestMapping("/student")
public class StuController {

    //@Autowired默认按类型装配， @Resource默认按名称装配，
    @Autowired private StuServiceImpl stuServiceimpl;
    @Resource private StuMapper stuMapper;

    @GetMapping("/index")
    public String index(){
        return "OK";
    }


    @PostMapping("/addAndUpdate") //添加和修改
    public Results saveAn(@RequestBody Student student){
        return Results.success( stuServiceimpl.saveAn(student));
    }

    @RequestMapping("/findAll")
    public List<Student> findAll(){
        return  stuServiceimpl.list();
    }

/*    @DeleteMapping("/{stuId}")  //真删除
    public Results deleteAnimal(@PathVariable Integer stuId){
        return  Results.success(stuServiceimpl.removeById(stuId)) ;
    }*/
    @DeleteMapping("/{stuId}") //假删除
    public Results deleteAnimal(@PathVariable Integer stuId){
        Student student = stuMapper.selectById(stuId);
        student.setDeleteFlage(1);
        stuMapper.updateById(student);
        return Results.success();
}


/*    @PostMapping("/deleteDuo") //真多选删除
    public Results deleteDuo(@RequestBody List<Integer> ids){
        return  Results.success( stuServiceimpl.removeByIds(ids));
    }*/

    @PostMapping("/deleteDuo")
    public Results deleteDuo(@RequestBody List<Integer> ids){
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("stu_id", ids);
        List<Student> stus = stuMapper.selectList(queryWrapper);
        for (Student student : stus) {
            student.setDeleteFlage(1);
            stuMapper.updateById(student);
        }
        return Results.success();
    }



    @GetMapping("/page")
    public IPage<Student> findPages(@RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize,
                                    @RequestParam(defaultValue = "") String stuName,
                                    @RequestParam(defaultValue = "") String sex,
                                    @RequestParam(defaultValue = "") String idNum,
                                    @RequestParam(defaultValue = "") String mobile
                                                                                    ){

        IPage<Student> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Student> queryWrapper=new QueryWrapper<>();

        queryWrapper.eq("delete_flage", 0);

        if(!"".equals(stuName)){
            queryWrapper.like("stu_name",stuName);
        }
        if(!"".equals(sex)){
            queryWrapper.like("sex",sex);

        }
        if(!"".equals(idNum)){
            queryWrapper.like("id_num",idNum);
        }
        if(!"".equals(mobile)){
            queryWrapper.like("mobile",mobile);
        }



        return  stuServiceimpl.page(page,queryWrapper);

    }

    @GetMapping("/export") //导出
    public void export(HttpServletResponse response) throws  Exception{
        //查询所有数据
        List<Student> list = stuServiceimpl.list();
        //通过工具类创建writer 写出到磁盘路径
        //ExcelWriter writer = ExcelUtil.getWriter("" + "/用户信息.xlsx");
        //在内存操作 写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("stuId","id");
        writer.addHeaderAlias("stuNum","学号");
        writer.addHeaderAlias("stuName","名字");
        writer.addHeaderAlias("mobile","手机号");
        writer.addHeaderAlias("sex","年龄");
        writer.addHeaderAlias("age","性别");
        writer.addHeaderAlias("idType","证件类型");
        writer.addHeaderAlias("idNum","证件号码");
        writer.addHeaderAlias("birthday","生日");
        writer.addHeaderAlias("detailAddr","籍贯");
        writer.addHeaderAlias("createDatee","创建日期");
        writer.addHeaderAlias("updateDate","修改日期");

        writer.write(list, true);

        //设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;" +
                "charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream, true);
        outputStream.close();
        writer.close();
    }

    @PostMapping("/import") //导入
    public Boolean imp(MultipartFile file) throws Exception{
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<Student> list = reader.readAll(Student.class);
        System.out.println(list);
        stuServiceimpl.saveBatch(list);
        return true;
    }


   @Autowired private StuService stuService;

    @PostMapping("/login")
    public Results login(@RequestBody StuDTO stuDTO) {
        String email =  stuDTO.getEmail();
        String password = stuDTO.getPassword();
        if (StrUtil.isBlank(email) || StrUtil.isBlank(password)) {
            return Results.error(Constants.CODE_400,"参数错误");
        }
        StuDTO dto= stuService.login(stuDTO);
        return  Results.success(dto);
    }

    @PostMapping("/register") //注册
    public Results register(@RequestBody StuDTO stuDTO){
        String email =  stuDTO.getEmail();
        String password = stuDTO.getPassword();
        if (StrUtil.isBlank(email) || StrUtil.isBlank(password)) {
            return Results.error(Constants.CODE_400,"参数错误");
        }
        return  Results.success(stuService.register(stuDTO));
    }

    @GetMapping("/{stuName}") //根据姓名查询和人信息
    public Results findOne(@PathVariable String stuName){

        QueryWrapper<Student> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("stu_name",stuName);
        return Results.success(stuService.getOne(queryWrapper)) ;
    }

/*

    @Autowired private StudentService studentService;
    //查询全部省
    @ResponseBody
    @PostMapping("/getProvinces")
    public Results getProvinces(){
        return studentService.getProvinces();
    }

    //根据省ID查市
    @ResponseBody
    @PostMapping("/getCities/{provinceId}")
    public List<Cities> getCities(@PathVariable("provinceId") Integer provinceId){
        //System.out.println("-----"+stuId);
        return studentService.getCities(provinceId);
    }

    //根据市查县
    @ResponseBody
    @PostMapping("/getAreas/{cityId}")
    public List<Areas> getAreas(@PathVariable("cityId") Integer cityId){
        //System.out.println("-----"+stuId);
        return studentService.getAreas(cityId);
    }

    //查看
    @ResponseBody
    @PostMapping("/stuOneId/{stuId}")
    public Results stuOneId(@PathVariable("stuId") Integer stuId){
        System.out.println("-----"+stuId);
        return studentService.stuOneId(stuId);
    }
*/


}
